<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/10
 * Time: 10:57
 */
namespace app\admin\controller;

use app\admin\model\AdminCook;
use app\admin\model\AdminWaiter;
use app\admin\model\MemberCook;
use app\admin\model\MemberWaiter;
use app\admin\model\Order;
use app\admin\model\OrderFoods;
use app\admin\model\ShopTable;
use think\Controller;
use think\Db;
use think\facade\Cache;
use app\index\model\WxSet;
use think\facade\Session;
class BaseController extends Controller
{

	protected $url;
    public function initialize(){
//        $access_token = Cache::store('redis')->get('access_token');
//        if (!$access_token){
//            $this->accessToken();
//        }
    	$this->url = 'http://'.$_SERVER['HTTP_HOST'];
        if(!Session::get('admin_id')){
            $this->redirect(url("login/login"));
        }
    }

//    public function accessToken(){
//        $ret = WxSet::get(1);
//        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$ret['appID']."&secret=".$ret['secret'];
//        $token = $this->curl($url);
//        if (array_key_exists("access_token",$token)){
//            Cache::store('redis')->set('access_token',$token['access_token'],7150);
//        }
//    }

    public function roleArray($data){
        $results = [];
        foreach ($data as $key => $value) {
            $results[$value['id']] = $value;
        }
        $tree = [];
        foreach ($results as $item) {
            if(isset($results[$item['pid']])){
                $results[$item['pid']]['children'][] = &$results[$item['id']];
            }else{
                $tree[] = &$results[$item['id']];
            }
        }
        $results = [];
        foreach ($tree as $value) {
            $value['children'] = isset($value['children'])?$this->formatMenus($value['children']):false;
            $results[] = $value;
        }
        return $results;
    }

    private function formatMenus($items,&$res = array()){
        foreach($items as $item){
            if(!isset($item['children'])){
                $res[] = $item;
            }else{
                $tem = $item['children'];
                unset($item['children']);
                $res[] = $item;
                $this->formatMenus($tem,$res);
            }
        }
        return $res;
    }



    public function shopTime($start,$end){
        $ret = strtotime($start);
        $ret2= strtotime($end);
        $today = strtotime(date("Y-m-d"),time());
        $ret = $ret - $today;
        $ret2 = $ret2 - $today;
        $ret = $ret."-".$ret2;
        return $ret;
    }

    public function shopTimeRestore($time){
        $time = explode("-",$time);
        $today = strtotime(date("Y-m-d"),time());
        $time[0] = $time[0] + $today;
        $time[1] = $time[1] + $today;
        $time[0] = date(' H:i:s',$time[0]);
        $time[1] = date(' H:i:s',$time[1]);
        $ret = implode('-',$time);
        return $ret;
    }

    public function del($name,$field,$id){
        $where = [$field=>$id];
        $ret = Db::name($name)->where($where)->delete();
        return $ret;
    }

    public function upload($file){
        $info = $file->move( '../public/uploads');
        if ($info) {
            $result = [
                'code'     => 0,
                'msg'      => '上传成功',
                'filename' => '/uploads/' . str_replace('\\', '/', $info->getSaveName())
            ];
        } else {
            $result = [
                'code' => -1,
                'msg'  => $file->getError()
            ];
        }
        return $result;
    }
    public function curl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }


    public function postCurl($url,$post){
        $data  = json_encode($post);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    public function waiter($table_id,$order_no){
        $table = ShopTable::where('id',$table_id)->find();
        if ($table['waiter_id'] == 0){
            return 1;
        }
        $order = Order::where('order_no',$order_no)->find();
        $ratio = AdminWaiter::get(1);
        if ($ratio['status'] == 1){
            $money = round($order['money'] * ($ratio['value']/100),2);
            $status = '订单';
        }elseif ($ratio['status'] == 2){
            $money = round($order['order_number'] * $ratio['money'],2);
            $status = '人数';
        }
        $data = [
            'user_id'=>$table['waiter_id'],
            'order_no'=>$order['order_no'],
            'total'=>$order['money'],
            'number'=>$order['order_number'],
            'money'=>$money,
            'status'=>$status,
            'create_time'=>time()
        ];
        $ret = MemberWaiter::create($data);
        if (!$ret){
            return 0;
        }
        return 1;
    }


    public function cook($food_id){
        $food = OrderFoods::where('id',$food_id)->find();
        if (!$food){
            return 0;
        }
        $ratio = AdminCook::get(1);
        if ($food['cook_id']){
            $money = round($food['food_price'] * $food['quantity'] * ($ratio['make']/100),2);
            $data = [
                'user_id'=>$food['cook_id'],
                'order_no'=>$food['order_no'],
                'food_name'=>$food['food_name'],
                'number'=>$food['quantity'],
                'money'=>$money,
                'status'=>1,
                'create_time'=>time(),
            ];
            MemberCook::create($data);
        }
        if ($food['inventor']){
            $money = round($food['food_price'] * $food['quantity'] * ($ratio['invent']/100),2);
            $data = [
                'user_id'=>$food['inventor'],
                'order_no'=>$food['order_no'],
                'food_name'=>$food['food_name'],
                'number'=>$food['quantity'],
                'money'=>$money,
                'status'=>2,
                'create_time'=>time(),
            ];
            MemberCook::create($data);
        }
        return 1;
    }

}